package cc.ncmqmctool

import android.Manifest
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.os.HandlerThread
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cc.ncmqmctool.common.NcmDump
import cc.ncmqmctool.common.QmcDump
import com.vanniktech.rxpermission.Permission
import com.vanniktech.rxpermission.RealRxPermission
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.io.FileFilter
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingDeque
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    /**
     * 是否删除原文件
     */
    private var shouldDeleteOrigin = true
    private val qqPath = Environment.getExternalStorageDirectory().absolutePath + "/qqmusic/song/"
    private val neteasePath =
        Environment.getExternalStorageDirectory().absolutePath + "/netease/cloudmusic/Music/"

    /**
     * 已执行完成的文件。
     */
    val executedFileList = mutableListOf<File>()

    private val adapter by lazy {
        object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun onCreateViewHolder(
                parent: ViewGroup,
                viewType: Int
            ): RecyclerView.ViewHolder {
                return object : RecyclerView.ViewHolder(
                    TextView(this@MainActivity).also {
                        it.textSize = 14F
                    }
                ) {}
            }

            override fun getItemCount(): Int {
                return executedFileList.size
            }

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                (holder.itemView as TextView).text = executedFileList.get(position).name
            }
        }
    }

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        RealRxPermission.getInstance(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe(Consumer<Permission> {
                if (it.state() != Permission.State.GRANTED) {
                    Toast.makeText(this, "请授予读写存储权限", Toast.LENGTH_LONG).show()
                    return@Consumer
                }
                initViews()
            })
    }

    private val blockQueue = LinkedBlockingDeque<File>()
    private var countDownLatch = CountDownLatch(2)

    private fun initViews() {
        rvList.layoutManager = LinearLayoutManager(this)
        rvList.adapter = adapter
        deleteOrigin.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            shouldDeleteOrigin = isChecked
        })
        startScan.setOnClickListener {
            blockQueue.clear()
            executedFileList.clear()
            tip.text = "开始处理..."
            thread {
                startScan(qqPath)
                startScan(neteasePath)
                countDownLatch.await()
                runOnUiThread {
                    tip.text = "处理完成！共处理${adapter.itemCount}个文件"
                }
            }
        }
    }

    private fun startScan(musicPath: String) {
        val musicFile = File(musicPath)
        val musicFileList = musicFile.listFiles(FileFilter {
            it.name.contains(".qmc", true) ||
                    it.name.contains(".ncm", true)
        })
        var executedCount = 0
        if (musicFileList == null || musicFileList.isEmpty()) {
            countDownLatch.countDown()
            return
        }
        blockQueue.addAll(musicFileList)
        thread {
            while (blockQueue.isNotEmpty()) {
                val targetFile = blockQueue.poll()
                if (targetFile != null) {
                    runOnUiThread {
                        tip.text = "正在处理:${targetFile.name}"
                    }
                    val isSuccess = dump(targetFile, musicFile)
                    if (shouldDeleteOrigin && isSuccess) {
                        targetFile.delete()
                    }
                    executedCount++
                    runOnUiThread {
                        executedFileList.add(targetFile)
                        adapter.notifyItemInserted(adapter.itemCount)
                    }
                }
            }
            countDownLatch.countDown()
        }
    }

    private fun dump(targetFile: File, outFile: File): Boolean {
        if (targetFile.name.contains(".ncm")) {
            return NcmDump.dump(targetFile, outFile)
        } else {
            QmcDump.dump(targetFile, outFile)
            return true
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        MenuInflater(this).inflate(R.menu.menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.help -> {
                AlertDialog.Builder(this).setMessage(
                    "点击“自动扫描并转换网易云、QQ音乐目录下歌曲”" +
                            "按钮，软件会自动扫描云音乐和QQ音乐下载目录下的加密歌曲并转换，您也可以将外部的文件拷贝到" +
                            "云音乐或者QQ音乐的下载目录下，点击按钮软会自动转换"
                ).show()
            }
        }
        return super.onOptionsItemSelected(item)
    }
}
